function hfile = hdr_LoadVoxelData(hfile)
% HDR::LoadVoxelData  - load Analyze image voxel data
%
% FORMAT:       hdr.LoadVoxelData;
%
% No input/output fields.

% Version:  v0.7c
% Build:    7120608
% Date:     Dec-06 2007, 8:23 AM CET
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'hdr')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end

% get HDR file name -> IMG file
hdrs = bvqxfile_getscont(hfile.L);
hdrc = hdrs.C;
fflp = hdrs.F;

% look in same folder
[ffpn, fflp, fflx] = fileparts(fflp);
ifname = [ffpn filesep fflp '.img'];
ifnamc = [ffpn filesep fflp '.IMG'];
if ~exist(ifname, 'file') == 2 && ...
    exist(ifnamc, 'file') == 2
    ifname = ifnamc;
end
if ~exist(ifname, 'file') == 2;
    error( ...
        'BVQXfile:FileNotFound', ...
        'Related %s.img file for %s%s not found.', ...
        fflp, fflp, fflx ...
    );
end

% get data size and type
try
    dsize = hdrc.ImgDim.Dim(2:hdrc.ImgDim.Dim(1)+1);
    tsize = prod(dsize);
catch
    error( ...
        'BVQXfile:BadFileContent', ...
        'Analyze ImgDim.Dim field error.' ...
    );
end
dtype = hdrc.ImgDim.DataType;
if isempty(dtype)
    dtype = 0;
end
endian = hdrs.C.Endian;
if dtype > 255
    dtype = fix(dtype / 256);
    switch lower(endian)
        case {'ieee-le'}
            endian = 'ieee-be';
        case {'ieee-be'}
            endian = 'ieee-le';
        otherwise
            error( ...
                'BVQXfile:InternalError', ...
                'Bad machine datatype/encoding syntax combination.' ...
            );
    end
end
[tmat, stype] = analyzetype(dtype);

% occupy mem
tmat(tsize) = tmat(1);

% open image file
try
    fid = fopen(ifname, 'rb', endian);
    fseek(fid, floor(abs(hdrc.ImgDim.VoxOffset)), 'bof');
    tmat(1:tsize) = fread(fid, [1, tsize], stype);
    fclose(fid);
catch
    error( ...
        'BVQXfile:FileNotReadable', ...
        'Error opening/reading image file data from %s.', ...
        ifname ...
    );
end

% reshape voxel data
tmat = reshape(tmat, dsize);

% put data in hfile/hfile
hdrc.VoxelData = tmat;
bvqxfile_setcont(hfile.L, hdrc);
